<?php
namespace Api\Controller;
use Common\Controller\FirstendController;

class ApiClassifyController extends FirstendController
{

    protected $apiKey = "e2d4ea3e54bdc5021c93786d04721351";

    /**
     * 20封顶 9块邮
     * @param int $offset
     * @param int $limitset
     * @internal param string $capping
     * @internal param string $free
     * @internal param string $hotSelling
     * @internal param coupon $string
     * @return array
     */
    public function shipping()
    {
        if(IS_POST) {
            $fp = 10;
            $tp = 20;
            $orderby = 'id';      // 默认的排序字段
            $orderway = 'desc';   // 默认的排序方式
            $offset = I('post.offset',0);
            $limitset = I('post.limitset',20);

            $odby = I('post.odby');
            if ($odby) {
                if($odby == 'addtime') {
                    $orderby = 'add_time';
                } elseif($odby == 'volume') {
                    $orderby = 'volume';
                }
            }

            if(I('post.param') == 'capping') {
                $where['coupon_price'] = array('between', array($fp, $tp)); // 10 - 20块之间
            } elseif(I('post.param') == 'free') {
                $where['coupon_price'] = array('lt',$fp);   // 9.9 包邮
            } elseif(I('post.param') == 'hotSelling'){
                $where['volume'] = array('gt',$fp);  //取销量大于10的
                $orderby = 'volume';   //按销量倒序
            } elseif(I('post.param') == 'coupon'){ //取优惠券
                $where['quan'] = array('egt',1);
                $orderby = 'quan';
            }else {
                $this->jsonReturn($this->getMsg('success','403','非法参数'));
            }

            $itemsModel = D('Items');

            $infos = $itemsModel->where($where)->order("tui desc,$orderby $orderway")
                ->limit($offset . ',' . $limitset)
                ->select();

            if(count($infos)>0) {
                $data = $this->transform($infos);
            } else {
                $this->jsonReturn($this->getMsg('success','404','not found'));
            }
            $this->jsonReturn($this->getMsg('success','200',$data));
        } else {
            $this->jsonReturn($this->getMsg('success','403','非法请求'));
        }
    }
    /**
     * 搜索
     */
    public function key_search($offset=1,$limitset=20)
    {
        $itemsModel = D('Items');
        $keywords = I('get.key');

        if(empty($keywords)) {
            $this->jsonReturn($this->getMsg('success','200','暂无数据!'));
        }

        $where['title'] = array('like',"%$keywords%");
        $infos = $itemsModel->where($where)->limit($offset . ',' . $limitset)->select();
        $data = $this->transform($infos);
        $this->jsonReturn($this->getMsg('success','200',$data));
    }

    /**
     * 第四个大类  超美棉衣
     */
    public function getFour()
    {
        if(IS_POST) {
            $id = 21;
            $offset = I('post.offset',0);
            $limitset = I('post.limitset',20);
            $catModel = D('items_cate');
            $itemsModel = D('Items');
            $catInfo = $catModel->where(['id'=>$id])->find();
            $title = $catInfo['name'];
            $logo = $catInfo['logo'];
            $desc = $catInfo['seo_title'];

            $odby = I('post.odby');
            $orderby = 'id';      // 默认的排序字段
            $orderway = 'desc';   // 默认的排序方式
            if ($odby) {
                if($odby == 'addtime') {
                    $orderby = 'add_time';
                } elseif($odby == 'volume') {
                    $orderby = 'volume';
                }
            }

            $infos = $itemsModel->where(['cate_id'=>$id])->order("tui desc,$orderby $orderway")->limit($offset . ',' . $limitset)->select();

            if(count($infos)>0) {
                $data = $this->transform($infos);
            } else {
                $this->jsonReturn($this->getMsg('success','404','not found'));
            }
            $arr = [
                'status' => 'success',
                'status_code' => 200,
                'title' => $title,
                'logo' => $logo,
                'desc' => $desc,
                'data' => $data,
            ];
            $this->jsonReturn($arr);
        }

        $this->jsonReturn($this->getMsg('success','403','非法请求'));

    }

    /**
     * 获取分类
     */
    public function getClassification()
    {
        if(IS_POST) {
            $itemsModel = D('items_cate');
            $itemsInfos = $itemsModel->where(['status'=>1])->select();
            $arr = [];
            foreach($itemsInfos as $info) {
                $data['id'] = $info['id'];
                $data['pid'] = $info['pid'];
                $data['title'] = $info['name'];
                $data['imgurl'] = $info['logo'];
                array_push($arr,$data);
            }
            $arr = $this->_getTree($arr);
            $this->jsonReturn($this->getMsg('success','200',$arr));
        }
        $this->jsonReturn($this->getMsg('success','403','非法请求'));
    }
    /**
     * 获取分类下的商品
     */
    public function getClassGoods()
    {
        if(IS_POST) {
            $itemsModel = D('Items');
            $key = I('post.key');
            $id = I('post.id');
            $offset = I('post.offset',0);
            $limitset = I('post.limitset',10);
            $odby = I('post.odby');
            $orderby = 'id';      // 默认的排序字段
            $orderway = 'desc';   // 默认的排序方式
            if ($odby) {
                if($odby == 'addtime') {
                    $orderby = 'add_time';
                } elseif($odby == 'volume') {
                    $orderby = 'volume';
                }
            }
            if ($id) {
                $where['cate_id'] = array('eq',$id);
            }
            $where['title'] = array('like', '%' . $key . '%');
            if($key) {
                $infos = $itemsModel->where($where)->order("tui desc,$orderby $orderway")->limit($offset . ',' . $limitset)->select();
                if(count($infos) > 0) {
                    $data = $this->transform($infos);
                    $this->jsonReturn($this->getMsg('success','200',$data));
                } else {
                    $this->jsonReturn($this->getMsg('success','201','暂无数据'));
                }
            } else {
                $this->jsonReturn($this->getMsg('success','201','参数错误'));
            }
        }
        $this->jsonReturn($this->getMsg('success','403','非法请求'));

    }

    /**
     * 获取商品详情 及猜你喜欢
     *
     * @param int id
     */
    public function getDetails()
    {
        if(IS_POST) {
            $id = I('post.id');
            $itemsModel = D('Items');
            $info = $itemsModel->where(['num_iid'=>$id])->find();

            //猜你喜欢
            $cat_id = $info['cate_id'];
            $likeData = $itemsModel->where(['cate_id'=>$cat_id])->order( "rand()")->limit(12)->select();

            //相似推荐
            //$tags = $info['tags'];

            if(is_null($info)){
                $this->jsonReturn($this->getMsg('success','404','not found'));
            }
            $shop = $this->getShop($id);
            $info = $this->getData($info);
            $info['shop'] = $shop;
            $data = $this->getInfo('success','200',$info,$this->transform($likeData));
            $this->jsonReturn($data);
        }
        $this->jsonReturn($this->getMsg('success','403','非法请求'));
    }

    /**
     * 获取首页Banner
     * @var [type]
     */
    public function getBanner()
    {
        $model = D('banner');
        $info = $model->where(['is_show'=>1])->select();
        $this->jsonReturn($this->getMsg('success',200,$info));
    }

    //宝贝详情
    public function getdesc()
    {
        if(IS_POST) {
            $id = I('post.id');
            $infoUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $id . '%22%7D';
            $comlist = file_get_contents($infoUrl);
            $comlist = json_decode($comlist,true);
            $tm = $comlist['data']['images'];
            if(is_null($tm)) {
                $this->jsonReturn($this->getMsg('success','404','not found'));
            }
            $this->jsonReturn($this->getMsg('success','200',$tm));
        }

    }

    /**
     * 获取VIP 商品
     */
    public function getPrivilege()
    {
        if(IS_POST) {
            $id = 22;
            $offset = I('post.offset',0);
            $limitset = I('post.limitset',20);
            $catModel = D('items_cate');
            $itemsModel = D('Items');
            $catInfo = $catModel->where(['id'=>$id])->find();
            $title = $catInfo['name'];

            $odby = I('post.odby');
            $orderby = 'id';      // 默认的排序字段
            $orderway = 'desc';   // 默认的排序方式
            if ($odby) {
                if($odby == 'addtime') {
                    $orderby = 'add_time';
                } elseif($odby == 'volume') {
                    $orderby = 'volume';
                }
            }

            $infos = $itemsModel->where(['cate_id'=>$id])->order("tui desc,$orderby $orderway")->limit($offset . ',' . $limitset)->select();
            if(count($infos)>0) {
                $data = $this->transform($infos);
            } else {
                $this->jsonReturn($this->getMsg('success','404','not found'));
            }
            $arr = [
                'status' => 'success',
                'status_code' => 200,
                'title' => $title,
                'data' => $data,
            ];
            $this->jsonReturn($arr);
        }
        $this->jsonReturn($this->getMsg('success','403','非法请求'));
    }

    /**
     * 全网搜索API
     * @return array data
     */
    public function search()
    {
        $key_word = I('get.keyword');
        $url = 'http://api.tkjidi.com/checkWhole?appkey='.$this->apiKey.'&k='.$key_word;
        $data = file_get_contents($url);
        $data = json_decode($data);

       //$this->jsonReturn($data->data);
        if(count($data->data) > 0) {
             $this->jsonReturn($this->getMsg('success','200',$data));
        } else {
            $this->jsonReturn($this->getMsg('success','404','not found'));
        }
    }

    public function transform(array $infos)
    {
        $arr = [];
        foreach($infos as $info) {
            $data = $this->getData($info);
            array_push($arr,$data);
        }
        return $arr;
    }

    private function _getTree($data, $pid=0, $level=0)
    {
        static $_ret = array();
        foreach ($data as $k => $v){
            if($v['pid'] == $pid){
                $v['level'] = $level;
                $_ret[] = $v;
                $this->_getTree($data, $v['id'], $level+1);
            }
        }
        return $_ret;
    }

    /**
     * 搜索词
     */
    public function getkeyword()
    {
       $model = D('keywords');
       $data = $model->where(['is_show'=>1])->field('id,keyword,hot')->select();
       $this->jsonReturn($this->getMsg('success','200',$data));
    }

    public function getShop($id)
    {
        $api = "http://hws.m.taobao.com/cache/wdetail/5.0/?id=$id&qq-pf-to=pcqq.temporaryc2c";
        $info = file_get_contents($api);
        $info = json_decode($info,true);
        $data['picsPath'] = $info['data']['itemInfoModel']['picsPath'];
        $data['itemTypeName'] = $info['data']['itemInfoModel']['itemTypeName'];
        $data['itemTypeLogo'] = $info['data']['itemInfoModel']['itemTypeLogo'];
        $data['nick'] = $info['data']['seller']['nick'];
        $data['goodRatePercentage'] = $info['data']['seller']['goodRatePercentage'];
        $data['evaluateInfo'] = $info['data']['seller']['evaluateInfo'];
        $data['picUrl'] = $info['data']['seller']['picUrl'];

        return $data;
    }

    /**
     * @param  int    goods_id   商品实际id
     * @param  string  title       商品名称
     * @param  string  intro        描述
     * @param  string  tags        标签
     * @param  string  nick        店铺名称
     * @param  string  shop_type      来源场家
     * @param  string  pic_url     图片地址
     * @param  string  item_url    商品地址
     * @param  int     price       原价
     * @param  int     ems       1包邮
     * @param  int     coupon_price   现价
     * @param  int     volume       销量
     * @param  int     desc       宝贝详情
     * @param  string     add_time    添加时间
     * @param  int     coupon    优惠券金额
     * @param  int     coupon_link    优惠券地址
     * @param  int     coupon_num    优惠券数量
     * @param  int     coupon_price    满多少包邮
     * @param  int     quan_receive    已领取数量
     * @param  int     quan_condition    使用条件
     * @return array
     */
    public function getData($info)
    {
        $data['id'] = $info['id'];
        $data['goods_id'] = $info['num_iid'];
        $data['title'] = $info['title'];
        $data['intro'] = $info['intro'];
        $data['tags'] = $info['tags'];
        $data['nick'] = $info['nick'];
        $data['shop_type'] = $info['shop_type'];
        $data['pic_url'] = $info['pic_url'];
        $data['click_url'] = $info['click_url'];
        $data['price'] = $info['price'];
        $data['coupon_price'] = $info['coupon_price'];
        $data['ems'] = $info['ems'];
        $data['volume'] = $info['volume'];
        $data['add_time'] = $info['add_time'];
        $data['coupon'] = $info['quan'];
        $data['coupon_link'] = $info['quanurl'];
        $data['coupon_num'] = $info['quan_surplus'];
        $data['quan_receive'] = $info['quan_receive'];
        $data['quan_condition'] = $info['quan_condition'];
        $data['coupon_start_time'] = $info['coupon_start_time'];
        $data['coupon_end_time'] = $info['coupon_end_time'];
        $data['tui'] = $info['tui'];
        return $data;
    }
}
